package com.wjw.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wjw.pojo.Book;
import com.wjw.pojo.Reader;
import com.wjw.service.BookService;
import com.wjw.service.ReaderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("book")
public class BookController {
    @Value("${location}")
    private String location;
    @Autowired
    private BookService bookService;

    @Autowired
    private ReaderService readerService;


    //展示所有图书
    @RequestMapping("listBook")
    public String listBook(@RequestParam(required = false,value ="pageNum",defaultValue = "1")Integer pageNum,
                           @RequestParam(required = false,value ="pageSize",defaultValue = "12")Integer pageSize, Model model, Book book,HttpSession session){
        if (pageNum<0 || pageNum.equals("") || pageNum==null){
            pageNum=1;
        }
        if (pageSize<0 || pageSize.equals("") || pageSize==null){
            pageSize=12;
        }
        session.removeAttribute("msg");
        String currentUser = (String) session.getAttribute("currentUser");
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<Book>qw=new QueryWrapper<>();
        if (book.getBname()!=null){
            qw.like("bname",book.getBname());
        }
        qw.notLike("sharer",currentUser);
        qw.gt("stock",0);
        List<Book> list = bookService.list(qw);
        PageInfo<Book> pageInfo = new PageInfo<>(list);
        model.addAttribute("pageInfo",pageInfo);
        return "normalUserBookList";
    }

    @RequestMapping("preSaveBook")
    public String preSaveBook(){
        return "bookSave";
    }





    @RequestMapping("batchDeleteBook")
    @ResponseBody
    public String batchDeleteBook(String idList){
        String[] split = StrUtil.split(idList, ",");
        List<Integer>list=new ArrayList<>();
        for (String s : split) {
            if (!s.isEmpty()){
                int i = Integer.parseInt(s);
                list.add(i);
            }
        }
        boolean b = bookService.removeByIds(list);
        if (b){
            return "OK";
        }else {
            return "error";
        }
    }


    //查看图书详情
    @RequestMapping("toBookSingle/{bookId}")
    public String toFoodSingle(@PathVariable  Integer bookId,Model model){
        Book book = bookService.getById(bookId);
        model.addAttribute("book",book);
        QueryWrapper<Book>qw=new QueryWrapper<>();
        qw.eq("grade",book.getGrade());
        qw.eq("major",book.getMajor());
        qw.eq("semester",book.getSemester());
        List<Book> list = bookService.list(qw);
        model.addAttribute("bookList",list);
        return "book-single";
    }

    //我的分享
    @RequestMapping("listMyShare")
    public String listMyShare(@RequestParam(required = false,value ="pageNum",defaultValue = "1")Integer pageNum,
                              @RequestParam(required = false,value ="pageSize",defaultValue = "10")Integer pageSize, Model model, Book book,HttpSession session){
        if (pageNum<0 || pageNum.equals("") || pageNum==null){
            pageNum=1;
        }
        if (pageSize<0 || pageSize.equals("") || pageSize==null){
            pageSize=10;
        }
        String currentUser = (String) session.getAttribute("currentUser");
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<Book>qw=new QueryWrapper<>();
        if (book.getBname()!=null){
            qw.like("bname",book.getBname());
        }
        qw.eq("sharer",currentUser);
        List<Book> list = bookService.list(qw);
        PageInfo<Book> pageInfo = new PageInfo<>(list);
        model.addAttribute("pageInfo",pageInfo);
        return "myShare-list";
    }

    @RequestMapping("preShareBook")
    public String preShareBook(){
        return "myShareSave";
    }

    @RequestMapping("shareBook")
    public String saveBook(Book book, MultipartFile file,HttpSession session){
        String currentUser = (String) session.getAttribute("currentUser");
        book.setSharer(currentUser);
        transFile(book,file);
        boolean save = bookService.save(book);
        return "redirect:/book/listMyShare";

    }

    private void transFile(Book book, MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String suffix=originalFilename.substring(index);
        String prefix=System.nanoTime()+"";
        String path=prefix+suffix;
        File file1 = new File(location);
        if (!file1.exists()){
            file1.mkdirs();
        }
        File file2 = new File(file1, path);
        try {
            file.transferTo(file2);
        } catch (IOException e) {
            e.printStackTrace();
        }
        book.setBimage(path);
    }

    //删除我的分享
    @RequestMapping("delBook/{id}")
    public String delbook(@PathVariable Integer id){
        boolean b = bookService.removeById(id);
        return "redirect:/book/listMyShare";
    }
    //跳转到修改我的分享教材页面
    @RequestMapping("preUpdateBook/{id}")
    public String preUpdateBook( @PathVariable Integer id,Model model){
        Book book = bookService.getById(id);
        model.addAttribute("book",book);
        return "myShareUpdate";
    }
    //修改我的分享教材
    @RequestMapping("updateBook")
    public String updateBook(Book book){
        boolean b = bookService.updateById(book);
        return "redirect:/book/listMyShare";
    }


    //推荐教材
    @RequestMapping("recommendBook")
    public String recommendBook(HttpSession session,Model model){
        Integer userId = (Integer) session.getAttribute("userId");
        Reader reader = readerService.getById(userId);
        String grade = reader.getGrade();
        String major = reader.getMajor();
        String semester = reader.getSemester();
        QueryWrapper<Book>qw=new QueryWrapper<>();
        qw.eq("grade",grade);
        qw.eq("major",major);
        qw.eq("semester",semester);
        List<Book> list = bookService.list(qw);
        PageInfo<Book>pageInfo=new PageInfo<>(list);
        model.addAttribute("pageInfo",pageInfo);
        return "recommend-list";

    }

    //查看下学期课本
    @RequestMapping("nextSemester")
    public String nextSemester(HttpSession session,Model model){
        Integer userId = (Integer) session.getAttribute("userId");
        Reader reader = readerService.getById(userId);
        String grade = reader.getGrade();
        String semester = reader.getSemester();
        String major = reader.getMajor();
        QueryWrapper<Book>qw=new QueryWrapper<>();
        qw.eq("major",major);
        if (grade.equals("大一") && semester.equals("上学期")){
            qw.eq("semester","下学期");
            qw.eq("grade",grade);
        }else if (grade.equals("大一") && semester.equals("下学期")){
            qw.eq("semester","上学期");
            qw.eq("grade","大二");
        }else if (grade.equals("大二") && semester.equals("上学期")){
            qw.eq("semester","下学期");
            qw.eq("grade",grade);
        }else if (grade.equals("大二") && semester.equals("下学期")){
            qw.eq("semester","上学期");
            qw.eq("grade","大三");
        }else if (grade.equals("大三") && semester.equals("上学期")){
            qw.eq("semester","下学期");
            qw.eq("grade",grade);
        }else if (grade.equals("大三") && semester.equals("下学期")){
            qw.eq("semester","上学期");
            qw.eq("grade","大四");
        }else if (grade.equals("大四") && semester.equals("上学期")){
            qw.eq("semester","下学期");
            qw.eq("grade",grade);
        }else if (grade.equals("大四") && semester.equals("下学期")){
            qw.eq("semester","上学期");
            qw.eq("grade",grade);
        }
        List<Book> list = bookService.list(qw);
        PageInfo<Book>pageInfo=new PageInfo<>(list);
        model.addAttribute("pageInfo",pageInfo);
        return "nextSemesterBook";
    }
}
